var UUID = require('../../../utils/Math.uuid')
var {isPhoneAvailable} = require('../../../utils/util')
var app = getApp()
var delayflag

Page({
  data: {
    isFirst: '0',
    sexSets: [{
      value: '女',
      checked: 'false'
    },
      {
        value: '男',
        checked: 'false'
      },
      {
        value: '保密',
        checked: 'true'
      }],
    birthdaystr: '1990-01-01',
    birth: {
      year: '1990',
      month: '01',
      day: '01'
    },
    isAgree: '1',
    isAgree2: '1',
    rctype: '1',
    sum: '0',
    pay: '0',
    isPassword: true,
    tipshow: false,
    username: '',
    phone: '',
    msgCode: '',
    sexval: '2',
    cardNo: '',
    cardPwd: '',
    verifyTips: '获取验证码',
    timeflag: -1
  },
  onLoad: function () {
    var isFisrt = '0'
    if (app.globalData.personInfo.MOBILE === '') {
      isFisrt = '1'
    }
    this.setData({
      isFirst: isFisrt
    })
    this.loadBalance()
  },
  loadBalance: function () {
    var url = '/yuanmai_we/user/activityrecharge/list'
    app.get(url).then(res => {
      for (var i = 0; i < res.length; i++) {
        res[i].giveRecharge = parseInt(res[i].giveRecharge)
        res[i].recharge = parseInt(res[i].recharge).toString()
      }
      this.setData({
        sum: res[0].recharge,
        pay: res[0].pay,
        sumlist: res
      })
    })
  },
  onHide: function () {
    if (delayflag) {
      clearTimeout(delayflag)
    }
  },
  onUnload: function () {
    if (delayflag) {
      clearTimeout(delayflag)
    }
  },
  nameInput: function (e) {
    this.setData({
      username: e.detail.value
    })
  },
  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  codeInput: function (e) {
    this.setData({
      msgCode: e.detail.value
    })
  },
  radioChange: function (e) {
    var sexval = '0'
    if (e.detail.value === '男') {
      sexval = '1'
    }
    else if (e.detail.value === '保密') {
      sexval = '2'
    }
    this.setData({
      sexval: sexval
    })
  },
  bindDateChange: function (e) {
    var dateval = e.detail.value
    var vals = dateval.split('-')
    var birth = this.data.birth
    birth.year = vals[0]
    birth.month = vals[1]
    birth.day = vals[2]
    this.setData({
      birthdaystr: dateval,
      birth: birth
    })
  },
  setIsDefault: function () {
    var isAgree = this.data.isAgree
    if (isAgree === '1') {
      isAgree = '0'
    }
    else {
      isAgree = '1'
    }
    this.setData({isAgree: isAgree})
  },
  setIsDefault2: function () {
    var isAgree2 = this.data.isAgree2
    if (isAgree2 === '1') {
      isAgree2 = '0'
    }
    else {
      isAgree2 = '1'
    }
    this.setData({isAgree2: isAgree2})
  },
  changeRechageType: function (e) {
    var rctype = e.currentTarget.id
    if (rctype === this.data.rctype) {
      return
    }
    this.setData({
      rctype: rctype
    })
  },
  changeSum: function (e) {
    var sum = e.currentTarget.id
    var pay = e.currentTarget.dataset.pay
    if (sum === this.data.sum) {
      return
    }
    this.setData({
      sum: sum,
      pay: pay
    })
  },
  changeEyeOpen: function () {
    var isPassword = this.data.isPassword
    if (isPassword === true) {
      isPassword = false
    }
    else {
      isPassword = true
    }
    this.setData({isPassword: isPassword})
  },
  scanCard: function () {
    var that = this
    wx.scanCode({
      success: function (res) {
        that.setData({
          cardNo: res.result
        })
      }
    })
  },
  backToOnlineRecharge: function () {
    this.setData({
      rctype: '1'
    })
  },
  checkMoneyDetail: function () {
    wx.redirectTo({
      url: './moneydetail/moneydetail',
    })
  },
  setMoneyPwd: function () {
    wx.navigateTo({
      url: './password/password?target=set',
    })
  },
  checkRule: function () {
    this.setData({tipshow: true})
  },
  hideTipContent: function () {
    this.setData({tipshow: false})
  },
  submitInfo: function () {
    if (this.data.isAgree !== '1') {
      app.toast.error('请同意相关协议')
      return
    }
    if (this.data.username === '' || this.data.phone === '' || this.data.msgCode === '') {
      app.toast.error('信息不完整')
      return
    }
    if (!isPhoneAvailable(this.data.phone)) {
      app.toast.error('手机号码格式不正确')
      return
    }
    var url = '/yuanmai_we/usercenter/user/registerForVip'
    var params = {
      __zaofans: true,
      USERNAME: this.data.username,
      USERSEX: this.data.sexval,
      MOBILE: this.data.phone,
      USERBIRTHDAY: this.data.birthdaystr,
      CHECKCODE: this.data.msgCode
    }
    app.request(url, params).then(this.submitCallBack.bind(this))
  },
  submitCallBack: function (res) {
    if (res.success) {
      app.toast.success('保存成功')
      app.globalData.personInfo = {
        USERNAME: this.data.username,
        USERSEX: this.data.sexval,
        MOBILE: this.data.phone,
        USERBIRTHDAY: this.data.birthdaystr,
      }
      setTimeout(() => {
        this.setData({
          isFirst: '0'
        })
      }, 1000)
    } else {
      app.toast.error(res.error)
    }
  },
  msgPhoneInput: function (e) {
    this.setData({
      msgPhone: e.detail.value
    })
  },
  msgCodeInput: function (e) {
    this.setData({
      msgCode: e.detail.value
    })
  },
  getVerifyCode: function (e) {
    if (this.data.phone === '') {
      app.toast.error('请输入手机号码')
      return
    }
    if (!isPhoneAvailable(this.data.phone)) {
      app.toast.error('手机号码格式不正确')
      return
    }
    if (this.data.timeflag > 0) {
      return
    }
    this.startReductTime()

    var url = '/yuanmai_we/activity/sms/sendCheckCode'
    var property = {
      "MOBILE": this.data.phone,
      "ACTION": "updateMobile"
    }
    var params = {
      datas: JSON.stringify(property),
      __zaofans: true
    }
    app.request(url, params).then(this.sendMsgActionCallBack.bind(this))
  },
  sendMsgActionCallBack: function (res) {
    if (res.success) {
      app.toast.success('发送成功')
    }
    else {
      app.toast.error(res.errMsg)
    }
  },
  scanGift: function () {
    wx.navigateTo({
      url: '../stores/stores?target=gift',
    })
  },
  gotoDetail: function () {
    wx.navigateTo({
      url: '../stores/stores?url=http://mp.weixin.qq.com/s/Ay--lcYuEgCeesPmsUSftA',
    })
  },
  //---------------------充值-----------------------
  rechargeAction: function () {
    app.showLoading()
    var url = '/weappmall/user/order/create'
    var trade_no = "CZ" + UUID.uuid(30)
    var bodystr = this.data.sum + '元充值卡'
    var openid = app.globalData.openID
    var sessionid = app.globalData.sessionID
    var payfee = parseFloat(this.data.pay) * 100
    var params = {
      uname: "weappmall ",//固定值
      out_trade_no: trade_no,//CZ+30位随机数
      body: bodystr,//xxx元充值卡
      spbill_create_ip: "127.0.0.1",
      trade_type: "JSAPI",
      openId: openid,
      attach: sessionid,
      total_fee: payfee
    }
    app.request(url, params).then(this.rechargeCallBack.bind(this))
  },
  rechargeCallBack: function (res) {
    if (res.code === '0000') {
      var jsapi = res.data
      var packagestr = "prepay_id=" + jsapi.prepay_id
      wx.requestPayment({
        appId: 'wx93176ec2a9cee7e1',
        timeStamp: jsapi.timeStamp,
        nonceStr: jsapi.nonceStr,
        package: packagestr,
        signType: 'MD5',
        paySign: jsapi.paySign,
        success: res => {
          app.hideLoading()
          app.toast.success('支付成功')
          setTimeout(() => {
            wx.redirectTo({
              url: './moneydetail/moneydetail'
            })
          }, 1000)
        },
        fail: err => {
          app.hideLoading()
        }
      })
    } else {
      app.hideLoading()
    }
  },
  cardNoInput: function (e) {
    this.setData({
      cardNo: e.detail.value
    })
  },
  cardPwdInput: function (e) {
    this.setData({
      cardPwd: e.detail.value
    })
  },
  cardRecharge: function () {
    if (this.data.cardNo === '' || this.data.cardPwd === '') {
      app.toast.error('信息有误')
      return
    }
    var url = '/yuanmai_we/user/userinfo/codeinfo'
    var property = {
      code: this.data.cardNo,
      pwd: this.data.cardPwd
    }
    var params = {
      datas: JSON.stringify(property),
      __zaofans: true
    }
    app.showLoading()
    app.request(url, params).then(this.checkCardInfoCallBack.bind(this))
  },
  checkCardInfoCallBack: function (res) {
    app.hideLoading()
    if (res.result === 'success') {
      var that = this
      var msg = '充值金额' + res.money + '元，是否充值？'
      wx.showModal({
        title: '',
        content: msg,
        confirmColor: '#a08257',
        confirmText: '确认',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            that.doCardRecharge()
          }
        }
      })
    }
    else {
      var msgstr = res.msg ? res.msg : '卡号密码错误'
      app.toast.error(msgstr)
    }
  },
  doCardRecharge: function () {
    if (this.data.cardNo === '' || this.data.cardPwd === '') {
      app.toast.error('信息有误')
      return
    }
    var url = '/yuanmai_we/user/userinfo/usecode'
    var property = {
      code: this.data.cardNo,
      pwd: this.data.cardPwd
    }
    var params = {
      datas: JSON.stringify(property),
      __zaofans: true
    }
    app.showLoading()
    app.request(url, params).then(this.doCardRechargeCallBack.bind(this))
  },
  doCardRechargeCallBack: function (res) {
    app.hideLoading()
    if (res.result === 'success') {
      app.toast.success('充值成功')
      app.getUserInfo()
    }
    else {
      var msgstr = res.msg ? res.msg : '卡号密码错误'
      app.toast.error(msgstr)
    }
  },
  startReductTime: function () {
    var flag
    if (this.data.timeflag === -1) {
      flag = 60
    }
    else if (this.data.timeflag > 0) {
      flag = this.data.timeflag - 1
    }
    var tips = flag + '秒后重试'
    if (flag === 0) {
      flag = -1
      tips = '获取验证码'
    }
    this.setData({
      timeflag: flag,
      verifyTips: tips
    })
    if (flag < 0) {
      return
    }
    var that = this
    delayflag = setTimeout(() => {
      if (delayflag) {
        clearTimeout(delayflag)
        that.startReductTime()
      }
    }, 1000)
  },
  toContact: function () {
    wx.navigateTo({
      url: '../stores/stores?target=contact'
    })
  }
})
